/**
 * 实现了一个 简单的 LRUCache.
 * 
 */
export  default  class {

    /**
     * 最多存储 maxSize - 1个
     * @param maxSize {Number}
     * @param releaseCallback {Function}
     */
    constructor(maxSize = 20,releaseCallback){
        this.maxSize = maxSize;
        this.data = [];
        this.releaseCallback = releaseCallback; // 回收时的回调
    }


    /**
     *
     * @param key {string}
     * @param value {object}
     */
    set(key,value){
        let idx = -1;
        for(let i = 0,len = this.data.length; i < len; ++i){
            let obj = this.data[i];
            if(obj.key === key){
                idx = i;
                break;
            }
        }

        if(idx >= 0){
            // 找到了 先删除再移动到后面
            let obj = this.data[idx];
            this.data.splice(idx,1);
            this.data.push(obj);
        }else{
            // 没找到.
            this.data.push({key:key,value:value});

            if(this.data.length >= this.maxSize){
                // 删除第一个
                let firstObj = this.data.shift();
                if(this.releaseCallback){
                    this.releaseCallback(firstObj);
                }
            }
        }
    }

    get(key){
        let item = this.data.find(obj=>{
            return obj.key === key;
        });
        if(item){
            return item.value;
        }
        return null;
    }
}

